module crc8 (
    input wire [7:0] data_in,
    input wire clk,
    input wire flag,
    input wire reset,
    output wire [7:0] crc_out
);

reg [7:0] c;
reg [7:0] temp;
reg [7:0] d;

always @(posedge clk) begin
    d <= data_in;
end

always @(posedge clk or negedge reset) begin
    if (!reset) begin
        c <= 8'b0;
        temp <= 8'b0;
    end else if(flag) begin
        temp[0] = d[7] ^ d[6] ^ d[0] ^ c[0] ^ c[6] ^ c[7];
        temp[1] = d[6] ^ d[1] ^ d[0] ^ c[0] ^ c[1] ^ c[6];
        temp[2] = d[6] ^ d[2] ^ d[1] ^ d[0] ^ c[0] ^ c[1] ^ c[2] ^ c[6];
        temp[3] = d[7] ^ d[3] ^ d[2] ^ d[1] ^ c[1] ^ c[2] ^ c[3] ^ c[7];
        temp[4] = d[4] ^ d[3] ^ d[2] ^ c[2] ^ c[3] ^ c[4];
        temp[5] = d[5] ^ d[4] ^ d[3] ^ c[3] ^ c[4] ^ c[5];
        temp[6] = d[6] ^ d[5] ^ d[4] ^ c[4] ^ c[5] ^ c[6];
        temp[7] = d[7] ^ d[6] ^ d[5] ^ c[5] ^ c[6] ^ c[7];
        
        c <= temp;
    end
end

assign crc_out = c;

endmodule
